
package org.feit.findword.game;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Random;

public class LettersGenerator {
	private static final String TAG = "LettersGenerator";
	private ArrayList<ProbabilityQueue> mCharacters;

	public LettersGenerator(InputStream letter_stream) {

		BufferedReader br = new BufferedReader(new InputStreamReader(
				letter_stream));

		mCharacters = new ArrayList<ProbabilityQueue>();

		try {
			for (String line = br.readLine(); line != null; line = br
					.readLine()) {
				String chunks[] = line.split(" ");
				ProbabilityQueue pq = new ProbabilityQueue(chunks[0]);
				for (int i = 1; i < chunks.length; i++) {
					pq.addProb(chunks[i]);
				}
				mCharacters.add(pq);
			}
		} catch (Exception e) {
			// Log.e(TAG,"READING INPUT",e);
			// Checked exceptions considered harmful.
		}

	}

	
	public Board generateBoard(int rows, int cols, boolean isMK) {
		String letters[] = generateBoard(rows * cols);
		return new GenericBoard(rows, cols, letters, isMK);
	}

	public String[] generateBoard(int size) {
		int total = 0;
		Random rng = new Random();

		String board[] = new String[size];

		for (int i = 0; i < mCharacters.size(); i++) {
			total += mCharacters.get(i).peekProb();
		}

		// get the letters
		for (int i = 0; i < size; i++) {
			ProbabilityQueue pq = null;
			int remaining = rng.nextInt(total);
			//Log.d(TAG, "remaining: " + remaining + "/" + total);
			for (int j = 0; j < mCharacters.size(); j++) {
				pq = mCharacters.get(j);
				remaining -= pq.peekProb();
				if (pq.peekProb() > 0 && remaining <= 0) {
					break;
				}
			}
			board[i] = pq.getLetter();
			total -= pq.getProb();
			total += pq.peekProb();
		}

		// shuffle the letters
		for (int to = 15; to > 0; to--) {
			int from = rng.nextInt(to);
			String tmp = board[to];
			board[to] = board[from];
			board[from] = tmp;
		}

		return board;
	}

	private class ProbabilityQueue {
		private String letter;
		private LinkedList<Integer> probQueue;

		public ProbabilityQueue(String l) {
			letter = l;
			probQueue = new LinkedList<Integer>();
		}

		public String getLetter() {
			return letter;
		}

		public void addProb(String s) {
			probQueue.add(new Integer(s));
		}

		public int peekProb() {
			if (probQueue.isEmpty())
				return 0;
			return probQueue.peek().intValue();
		}

		public int getProb() {
			if (probQueue.isEmpty())
				return 0;
			return probQueue.remove().intValue();
		}

	}

}
